package com.instpower.things.instpower;

import com.instpower.things.transport.Response;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToByteEncoder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @ClassName InstpowerEncoder
 * @Author: hellmash@gmail.com
 * @Date: 2020/2/23
 * @Version: 1.0.0
 * @Description: TODO
 */
public class InstpowerMessageEncoder extends MessageToByteEncoder<Response> {

    private static final Logger logger = LoggerFactory.getLogger("SYS");

    @Override
    protected void encode(ChannelHandlerContext ctx, Response response, ByteBuf out) throws Exception {
        if (null != response) {
            String cmd = String.format("Command = %04x", response.getHeader().getCommand());
            logger.info("Message Encode And Send {} to {} " ,cmd , response.getHeader().getAddr());
            ByteBuf buf = response.encode().getOrignalBuffer();
            out.writeBytes(buf);
            buf.release();
        }else{
            logger.debug("Message Encode And Send None");
        }
    }
}
